<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="./socket.io.min.js"></script>
</head>
<body>
    <div id="loginDiv">
        <input type="text" placeholder="请输入昵称，按下回车进入聊天室 ">
    </div>
    <div id="roomDiv">
        <p>欢迎<span style="color:red">xxx</span>的到来！当前在线人数为<span style="color:green">10</span>人</p>
        <input placeholder="输入聊天信息" type="text"><button>发送</button><br/>
        <textarea id="room" rows="50" cols="50"></textarea>
    </div>
</body>
<script>
    const loginDiv = document.querySelector("#loginDiv");
    const roomDiv = document.querySelector("#roomDiv");
    const loginInput = loginDiv.querySelector("input");
    const spans = roomDiv.querySelectorAll("span");
    const room = roomDiv.querySelector("#room");
    const sendBtn = roomDiv.querySelector("button");
    const sayInput = roomDiv.querySelector("input");
    roomDiv.style.display = "none";
    loginInput.onkeyup= async function(e){
        if(e.keyCode === 13){
            const nickName =e.target.value.trim();
            const data = await fetch("/login",{
                method:"post",
                headers:{
                    "Content-Type":"application/json"
                },
                body:JSON.stringify({
                    nickName
                })
            }).then(value=>value.json());
            if(data.ok === 1){
                const ws = io.connect("/");
                ws.emit("intoRoom",nickName);
                ws.on("online",function(nickName,onlineNum){
                    // 1- 更新在线的人数
                    spans[1].innerText = onlineNum;
                    // 2- 更新聊天室的内容
                    room.value += nickName+"进入到了聊天室\n";
                })
                ws.on("quitRoom",function(nickName){
                    room.value+= nickName+"退出聊天室\n";
                })
                ws.on("sayAll",function(nickName,context){
                    room.value += nickName+"说："+context+"\n";
                })
                sendBtn.onclick = function(){
                    // 收集信息：sayInput
                    ws.emit("say",sayInput.value.trim());
                }
                spans[0].innerText = nickName;
                // 隐藏登陆
                loginDiv.style.display = "none";
                // 显示房间
                roomDiv.style.display = "block";
            }else{
                alert(data.msg);
            }


        }
    }
</script>
</html>